import { Alert, Button, Checkbox, Icon, Modal, Progress, Row, Table, Tooltip, Typography, message, notification } from 'antd'
import { useState } from 'react'
import { useRequest } from 'ahooks'
import ComboGrid from '../Transformer/components/ComboGrid'
import { VersionStateMap } from '../ProcessManager/ProcessVersion/VersionPageTable'
import ProcessStatus from './ProcessStatus'
import Space from '@/components/Space'
import request from '@/utils/request'
import Ellipsis from '@/components/Ellipsis'
import { exportToCsv } from '@/utils/utils'

const { Text } = Typography

const columns = [
  {
    dataIndex: 'processLogId',
    title: '流程日志ID',
  },
  {
    dataIndex: 'instanceId',
    title: '实例ID',
  },
  {
    title: '异常编码',
    dataIndex: 'errorCode',
  },
  {
    title: '异常描述信息',
    dataIndex: 'errorDesc',
    render: text => <Ellipsis tooltip={text} length={20}>{text}</Ellipsis>,
  },
  {
    dataIndex: 'status',
    title: '执行状态',
    render: status => <ProcessStatus status={status} />,
  },
]

export default function BatchReRunModal({ isOpen, onCancel, data: { selectedRows = [] } }) {
  const [failures, setFailures] = useState([])
  const [end, setEnd] = useState(false)
  const [done, setDone] = useState(0)
  const total = selectedRows.length
  const percent = done / total * 100
  const [updateStatusWhenRetrySuccess, setUpdateStatusWhenRetrySuccess] = useState(true)
  const [processVersionId, setProcessVersionId] = useState()
  const { loading, runAsync } = useRequest(() => request.post('/processLog/batchReRun', {
    data: {
      rows: selectedRows,
      updateStatusWhenRetrySuccess,
      processVersionId,
    },
    timeout: 1000 * 60 * 10, // 10分钟超时
  }), { manual: true })

  if (!selectedRows.length)
    return null

  const handleCancel = () => {
    onCancel()
    setUpdateStatusWhenRetrySuccess(true)
    setProcessVersionId(undefined)
    setDone(0)
    setEnd(false)
    setFailures([])
  }
  const start = () => {
    if (!processVersionId) {
      message.warning('请选择重演版本号')
      return
    }
    let timer
    runAsync()
      .then((res) => {
        setDone(total)
        if (res && res.length === 0) {
          notification.success({
            message: '批量重演全部成功',
          })
          handleCancel()
          return
        }
        setFailures(res)
        setEnd(true)
      })
      .finally(() => {
        clearInterval(timer)
      })
    timer = setInterval(() => {
      request.get('/processLog/getBatchReRunCount').then((res) => {
        setDone(res)
      })
    }, 1000)
  }

  const handleDownload = () => {
    exportToCsv(columns, failures, `批量重演失败记录_${new Date().getTime()}`)
  }

  return (
    <Modal title="批量重演" width={800} visible={isOpen} maskClosable={false} closable={false} destroyOnClose
      footer={
        <Row type="flex" justify="space-between" align="middle">
          <Space style={{ display: 'flex', alignItems: 'center' }}>
            <Checkbox
              checked={updateStatusWhenRetrySuccess}
              onChange={e => setUpdateStatusWhenRetrySuccess(e.target.checked)}
            />
            <span>重演成功时，更新日志状态</span>
            <Tooltip title="如果重演成功，则将当前日志的状态更新为「重演成功」">
              <Icon style={{ opacity: '.5', cursor: 'help' }} type="question-circle-o" />
            </Tooltip>
          </Space>

          <div>
            <span className="mr">
              重演版本号<Tooltip title="基于某个版本的流程进行重演">
                <Icon style={{ opacity: '.5', cursor: 'help', marginLeft: 3, marginRight: 2 }} type="question-circle-o" />
              </Tooltip>：
              <ComboGrid
                style={{ width: 75 }}
                url={`/process/listVersions?processId=${selectedRows[0].processId}`}
                method="get"
                popupStyle={{ width: 400 }}
                placeholder="--请选择--"
                search={false}
                destroyPopupOnHide
                label="versionNumber"
                rowKey="versionId"
                pick="radio"
                value={[{ versionId: processVersionId }]}
                onChange={v => setProcessVersionId(v[0].versionId)}
                columns={[
                  {
                    title: '版本号',
                    dataIndex: 'versionNumber',
                  },
                  {
                    title: '版本状态',
                    dataIndex: 'versionState',
                    render: text => VersionStateMap[text],
                  },
                  {
                    title: '创建时间',
                    dataIndex: 'createDate',
                  },
                ]}
                slickTableProps={{ allowClear: false }}
              />
            </span>
            <Button type="default" onClick={handleCancel} disabled={loading}>
              取消
            </Button>
            {!end && <Button type="primary" onClick={start} loading={loading}>
              开始
            </Button>}
          </div>
        </Row>
      }>
      <Alert style={{ marginBottom: 16 }} message={<>在批量重演过程中，请不要<Text type="danger" strong>刷新</Text>或<Text type="danger" strong>关闭</Text>当前页面，以免进度丢失！</>} type="error" showIcon closable />
      <span>当前选中日志数量：{total}</span>
      <span style={{ marginLeft: 20 }}>重演进度：{done}/{total}</span>
      <Progress
        strokeColor={{
          from: '#108ee9',
          to: '#87d068',
        }}
        percent={percent.toFixed(0)}
        status="active"
      />
      {failures.length > 0 && (
        <div className='margin-top'>
          <div>重演结束，收集到 <Text type="danger" strong>{failures.length}</Text> 条失败记录：<a onClick={handleDownload}>下载查看</a></div>
          <Table className='margin-top' dataSource={failures} columns={columns} />
        </div>
      )}
    </Modal>
  )
}
